
package com.core.handle;

import com.core.utils.GsonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * @ClassName TypeHandler
 * @Description TODO
 * @Author fyx
 * @Date 2021/9/24 11:33
 * @Version 1.0
 **/

public class JsonTypeHandler<T> extends BaseTypeHandler<T> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Object parameter,
                                    JdbcType jdbcType) throws SQLException {
        //ORM Object R Model
            ps.setString(i, GsonUtils.toJsonStr(parameter));

    }

    @Override
    public T getNullableResult(ResultSet rs, String columnName)
            throws SQLException {
        String data = rs.getString(columnName);
        System.out.println("2222");
        return StringUtils.isBlank(data) ? null : GsonUtils.fromJson(data, (Class<T>) getRawType());
    }

    @Override
    public T getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String data = rs.getString(columnIndex);
        System.out.println("33333");
        return StringUtils.isBlank(data) ? null : GsonUtils.fromJson(data, (Class<T>) getRawType());
    }

    @Override
    public T getNullableResult(CallableStatement cs, int columnIndex)
            throws SQLException {
        String data = cs.getString(columnIndex);
        System.out.println("44444");
        return StringUtils.isBlank(data) ? null : GsonUtils.fromJson(data, (Class<T>) getRawType());
    }
}

